    //
//  LZUserInfoPresenter.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/12/21.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZUserInfoPresenter.h"
#import "NetworkServiceManager.h"
#import "NSString+Additions.h"

#import "LZUserModel.h"
#import "MJExtension.h"
#import "GVUserDefaults+LZProperties.h"

extern NSString *customer;

static NSString *const kUserValidateCodeUrl     = @"/clientuser/verificationCode";      // 根据手机号及验证码类型获取验证码
static NSString *const kUserLoginUrl            = @"/clientuser/login";                 // 用户使用用户名密码登录/快捷登录
static NSString *const kUserRegisterUrl         = @"/clientuser/register";              // 客户端用户注册
static NSString *const kUserThirdLoginUrl       = @"/clientuser/thirdLogin";            // 第三方账户登录

static NSString *const kUserMyInfo                  = @"/clientcustomerUser/myInfo";        // 获取用户信息
static NSString *const kUserChangeUserPhoto         = @"/clientuser/changeUserPhoto";       // 修改头像
static NSString *const kUserUpdateNickName          = @"/clientuser/updateNickName";        // 修改昵称
static NSString *const kUserResetPassword           = @"/clientuser/resetPassword";         // 修改密码
static NSString *const kUserValidateCellPhone       = @"/clientuser/validateCellPhone";     // 修改手机号时身份验证
static NSString *const kUserBindNewCellPhone        = @"/clientuser/bindNewCellPhone";      // 绑定新手机
static NSString *const kUserInitializePassword      = @"/clientuser/initializePassword";    // 初始化密码
static NSString *const kUserForgetMobilePassword          = @"/clientuser/forgetPassword";        // 手机号忘记密码校验
static NSString *const kUserForgetMailPassword          = @"/clientuser/forgetPasswordEmail";     // 邮箱忘记密码校验
static NSString *const kUserValidateUserName    = @"/clientuser/validateUser";  // 验证要绑定的新手机号是否已存在
static NSString *const kAreaCodeURL = @"/clientBasisCountryCode/list"; //区号选择
static NSString *const kUserBindEmail       = @"/clientuser/bindOrUpdateEmail";     // 绑定or更新邮箱地址
static NSString *const kUserBindThirdParty       = @"/clientuser/bindThirdParty";     // 绑定第三方账号
static NSString *const kUserUnBindThirdParty       = @"/clientuser/unbundle";     // 解绑第三方账户
static NSString *const kCheckUnReadMsgURL = @"/clientSellerMsg/unReadCnt";  //检查用户是否有未读消息

@implementation LZUserInfoPresenter

//根据类型，获取验证码
- (void)userGetVerificationCodeType:(NSString *)type
                        andPhoneNum:(NSString *)phoneNum
                          onSuccess:(PresenterCommonSuccess)success
                             onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserValidateCodeUrl);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:type          forKey:@"validateCodeType"];
    [params setObject:phoneNum      forKey:@"cellphone"];
    if ([[LZLanguageManager shareInstance] getLanguageType] == LanguageType_Ar) {
        [params setObject:[NSString stringWithFormat:@"2"] forKey:@"languageType"];
    } else {
        [params setObject:[NSString stringWithFormat:@"1"] forKey:@"languageType"];
    }
    
    DLog(@"获取验证码：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//注册
- (void)userRegisterCellPhone:(NSString *)phoneNum
                     andEmail:(NSString *)email
                  andPassword:(NSString *)password
          andVerificationCode:(NSString *)verifiCode
                 andonSuccess:(PresenterCommonSuccess)success
                       onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer, kUserRegisterUrl);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    
    [params setObject:phoneNum?:@"" forKey:@"cellphone"];
    [params setObject:email?:@"" forKey:@"email"];
    [params setObject:password?:@"" forKey:@"password"];
    [params setObject:verifiCode?:@"" forKey:@"validateCode"];
    
    DLog(@"注册：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        DLog(@"%@", resultData);
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        DLog(@"%@", error);
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//登录
- (void)userLoginCellPhone:(NSString *)phoneNum
   andPasswordOrVerifiCode:(NSString *)passwordOrVerifiCode
              andLoginType:(NSInteger)loginType
                 onSuccess:(PresenterCommonSuccess)success
                    onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer, kUserLoginUrl);
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    
    if(loginType == 1) {
        [params setObject:phoneNum forKey:@"userName"];
        [params setObject:passwordOrVerifiCode forKey:@"password"];
        [params setObject:[NSString stringWithFormat:@"%ld", (long)loginType] forKey:@"loginType"];
    }
    else if (loginType == 2) {
        [params setObject:phoneNum forKey:@"cellPhone"];
        [params setObject:passwordOrVerifiCode forKey:@"validateCode"];
        [params setObject:[NSString stringWithFormat:@"%ld", (long)loginType] forKey:@"loginType"];
    }
    
    DLog(@"登陆：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//第三方登录
- (void)userThirdPartLoginCellPhone:(NSMutableDictionary *)dataDict
                          onSuccess:(PresenterCommonSuccess)success
                             onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer, kUserThirdLoginUrl);
    NSMutableDictionary * params = [dataDict mutableCopy];
    
    DLog(@"第三方登陆：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//获取用户信息
- (void)userGetUserInfoBlockonSuccess:(PresenterCommonSuccess)success
                               onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserMyInfo);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];
    
    DLog(@"获取用户信息：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            
            NSDictionary *dataDic = (NSDictionary *)resultData;
            LZCurrentUserInfo *userInfo = [LZCurrentUserInfo mj_objectWithKeyValues:dataDic[@"data"]];
            if (userInfo) {
                [GVUserDefaults standardUserDefaults].userId = userInfo.userId;
                [[LZUserModel Instance] saveUserInfo:userInfo];
            }
            
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//修改头像
- (void)userChangeHeadImageFilePath:(NSString *)filePath
                          onSuccess:(PresenterCommonSuccess)success
                             onFail:(PresenterCommonFail)fail {

    NSString * urlStr = COMBINATION(customer,kUserChangeUserPhoto);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:filePath forKey:@"filePath"];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];
    
    DLog(@"修改头像：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//更改昵称
- (void)userChangeNickname:(NSString *)nickName
                 onSuccess:(PresenterCommonSuccess)success
                    onFail:(PresenterCommonFail)fail {

    NSString * urlStr = COMBINATION(customer,kUserUpdateNickName);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:nickName forKey:@"nickname"];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];
    
    DLog(@"更改昵称：urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//更改密码
- (void)userChangePassword:(NSString *)oldPassword
            andNewPassword:(NSString *)newPassword
                 onSuccess:(PresenterCommonSuccess)success
                    onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserResetPassword);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:[LZUserModel Instance].userInfo.userName forKey:@"userName"];
    [params setObject:oldPassword forKey:@"oldPassword"];
    [params setObject:newPassword forKey:@"newPassword"];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];
    
    DLog(@"更改密码:urlStr：%@ \r\n params：%@", urlStr, params);
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//修改手机号时身份验证
- (void)userChangeMoblieNumIDCheck:(NSString *)moblieNum
                     andVerifiCode:(NSString *)verifiCode
                         onSuccess:(PresenterCommonSuccess)success
                            onFail:(PresenterCommonFail)fail {

    NSString * urlStr = COMBINATION(customer,kUserValidateCellPhone);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:moblieNum forKey:@"cellphone"];
    [params setObject:verifiCode forKey:@"validateCode"];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];
    
    DLog(@"修改手机号时身份验证:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//绑定新手机
- (void)userChangeMoblieNumLinkNew:(NSString *)moblieNum
                     andVerifiCode:(NSString *)verifiCode
                         onSuccess:(PresenterCommonSuccess)success
                            onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserBindNewCellPhone);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:moblieNum forKey:@"cellphone"];
    [params setObject:verifiCode forKey:@"validateCode"];
    [params setObject:[LZUserModel Instance].userToken forKey:@"token"];

    DLog(@"绑定新手机:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//初始化密码
- (void)userInitPasswordWithMoblieNum:(NSString *)moblieNum
                          andPassword:(NSString *)password
                            onSuccess:(PresenterCommonSuccess)success
                               onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserInitializePassword);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:moblieNum forKey:@"userName"];
    [params setObject:password forKey:@"password"];
    
    DLog(@"初始化密码:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//手机号忘记密码校验
- (void)userForgetMobilePasswordWith:(NSString *)mobileNum
                 andVerifiCode:(NSString *)verifiCode
                     onSuccess:(PresenterCommonSuccess)success
                        onFail:(PresenterCommonFail)fail {

    NSString * urlStr = COMBINATION(customer,kUserForgetMobilePassword);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:mobileNum forKey:@"cellphone"];
    [params setObject:verifiCode forKey:@"validateCode"];
    
    DLog(@"忘记密码验证:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//邮箱忘记密码校验
- (void)userForgetMailPasswordWith:(NSString *)email
                 andVerifiCode:(NSString *)verifiCode
                     onSuccess:(PresenterCommonSuccess)success
                        onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserForgetMailPassword);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:email forKey:@"email"];
    [params setObject:verifiCode forKey:@"validateCode"];
    
    DLog(@"忘记密码验证:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//验证用户是否存在（包括手机号，邮箱，用户名）---不存在则返回"statusCode":"2000000"
- (void)userValidateUserNameWith:(NSString *)userName
                           onSuccess:(PresenterCommonSuccess)success
                              onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserValidateUserName);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:userName forKey:@"userName"];
    
    DLog(@"验证要绑定的新手机号是否已存在:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        SAFE_BLOCK_INVOKE(success, resultData);
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

#pragma mark - 区号获取
- (void)getAreaCodeSuccess:(void (^)(NSArray *))successBlock Failure:(PresenterCommonFail)failureBlock
{
    NSString *urlStr = COMBINATION(customer,kAreaCodeURL);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:nil success:^(NSURLSessionDataTask *task, id resultData) {
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:failureBlock]) {
            NSArray *resultArr = resultData[@"data"];
            if (successBlock) {
                successBlock(resultArr);
            }
        }
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        if (failureBlock) {
            failureBlock(error.description);
        }
    }];
}

// 绑定or更新邮箱地址
- (void)bindEmailWithOldEmail:(NSString *)oldEmail
                  andNewEmail:(NSString *)newEmail
                    onSuccess:(PresenterCommonSuccess)success
                       onFail:(PresenterCommonFail)fail {
    
    NSString * urlStr = COMBINATION(customer,kUserBindEmail);
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    if (oldEmail) {
        params[@"oldEmail"] = oldEmail;
    }
    
    if (newEmail) {
        params[@"newEmail"] = newEmail;
    }
    
    params[@"token"] = [LZUserModel Instance].userToken;
    
    DLog(@"绑定or更新邮箱地址:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

// 绑定第三方账号
- (void)bindThirdPartyAccountWithParams:(NSMutableDictionary *)params
                              onSuccess:(PresenterCommonSuccess)success
                                 onFail:(PresenterCommonFail)fail{
    
    NSString * urlStr = COMBINATION(customer,kUserBindThirdParty);
    
    if (params == nil) {
        params = [@{} mutableCopy];
    }
    
    params[@"token"] = [LZUserModel Instance].userToken;
    
    DLog(@"绑定第三方账号:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

// 解绑第三方账号
- (void)unBindThirdPartyAccountWithPartyAccount:(NSString *)partyAccount
                              onSuccess:(PresenterCommonSuccess)success
                                 onFail:(PresenterCommonFail)fail{
    
    NSString * urlStr = COMBINATION(customer,kUserUnBindThirdParty);
    
    NSDictionary *params = @{@"partyAccount":partyAccount,
                             @"token":[LZUserModel Instance].userToken};
    
    DLog(@"绑定第三方账号:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fail]) {
            SAFE_BLOCK_INVOKE(success, resultData);
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fail, error.localizedDescription);
    }];
}

//检查用户是否有未读消息
- (void)checkUserHaveUnReadMsg:(void (^)(NSInteger))successBlock failure:(PresenterCommonFail)fialBlock
{
    NSString * urlStr = COMBINATION(customer,kCheckUnReadMsgURL);
    
    if ([LZUserModel Instance].userToken.length <= 0) {
        return;
    }
    
    NSDictionary *params = @{@"token":[LZUserModel Instance].userToken};
    
    DLog(@"检测用户是否有未读消息:urlStr：%@ \r\n params：%@", urlStr, params);
    
    [[NetworkServiceManager manager] executePostTask:urlStr parameters:params success:^(NSURLSessionDataTask *task, id resultData) {
        
        if ([LZBasePresenter isRequestStatusCodeCorrect:resultData fail:fialBlock]) {
            NSInteger cc = [resultData[@"data"][@"unReadCnt"] integerValue];
            if (successBlock) {
                successBlock(cc);
            }
        }
        
    } fail:^(NSURLSessionDataTask *task, NSError *error) {
        SAFE_BLOCK_INVOKE(fialBlock, error.localizedDescription);
    }];

}


@end
